package com.alex.springboot.system.shiro;

import java.io.PrintWriter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.context.annotation.Bean;

import com.alex.springboot.system.enums.ResultStatusCode;
import com.alex.springboot.system.vo.Result;
import com.alibaba.fastjson.JSON;
/**
 * 权限拦截配置
 * 	注意：在配置bean时，将bean配置在了shiroConfig 中 有bean注解导致shiro 先走了拦截器，默认配置没有起作用。
 * 		配置这个需要拦截器有两种
 * 		1.在拦截文件中配置如下，
 * 		2.在shiroConfig配置，但不要加bean注解
 * @author yzl
 *
 */
public class ShiroFormAuthenticationFilter extends FormAuthenticationFilter {
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = getSubject(request, response);
        System.out.println(subject.isAuthenticated() );
        System.out.println(subject.isRemembered());
        if(subject.isAuthenticated() || subject.isRemembered()) {
            //如果登录了，直接进行之后的流程
            return true;
        }
        
        subject.logout();
 
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.println(JSON.toJSONString(new Result(ResultStatusCode.INVALID_TOKEN)));
        out.flush();
        out.close();
 
        return false;
    }
    
    @Bean
	public ShiroFormAuthenticationFilter shiroFormAuthenticationFilter() {
		ShiroFormAuthenticationFilter shiroFormAuthenticationFilter = new ShiroFormAuthenticationFilter();
		shiroFormAuthenticationFilter.setEnabled(false);
		return shiroFormAuthenticationFilter;
	}
}
